﻿using DAL;
using MS_Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MS_UI
{
    class InsertData
    {
        System.Timers.Timer t;
        int count = 0;
        public InsertData(int interval)
        {
            t = new System.Timers.Timer(interval);
            t.Elapsed += T_Elapsed;
            t.AutoReset = true;
            t.Enabled = true;
            t.Start();
            count = CommonMethod.CacheCount;
        }

        private void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (CommonMethod.CommOK)
            {
                // 插入数据
                InsertActualData();
            }
        }
        private void InsertActualData()
        {
            if (CommonMethod.CurrentValue!= null & CommonMethod.CurrentValue.Count>0)
            {
                List<string> sqlList = new List<string>();
                List<Cache> Cache = new List<Cache>();
                foreach (Variable_Modbus item in CommonMethod.FileVarModbusList)
                {
                    string varName = item.VarName;
                    string remark = item.Note;
                    string sql = "insert into ActualData(InsertTime,Varname,Value,Remark) values('{0}','{1}','{2}','{3}');";
                    double value = 0.0;
                    if (!CommonMethod.CurrentValue.ContainsKey(varName) || CommonMethod.CurrentValue[varName] == null)
                    {
                        value = 0.0;
                    }
                    else
                    {
                        value = Convert.ToDouble(CommonMethod.CurrentValue[varName]);
                    }
                    DateTime dt = DateTime.Now;
                    sql = string.Format(sql,DateTime.Now,varName,value,remark);
                    sqlList.Add(sql);
                    Cache.Add(new Cache()
                    {
                        InserTime = dt,
                        VarName = varName,
                        Value = value.ToString(),
                        Remark = remark,
                    }) ;
                }
                SQLHelper.UpdateByTran(sqlList);
                if (CommonMethod.CacheList.Count <= count)
                {
                    CommonMethod.CacheList.Add(Cache);
                }
                else
                {
                    CommonMethod.CacheList.RemoveAt(0);
                    CommonMethod.CacheList.Add(Cache);
                }
            }
        }
    }
}
